import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  // 最大级别的规则，对应的组件，会显示在App.vue中
  // 登录
  { path: '/login', component: () => import('@/views/MyLogin.vue') },
  // 注册
  { path: '/reg', component: () => import('@/views/Reg.vue') },
  // 首页
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      { path: 'home', component: () => import('@/views/Chart.vue') },
      { path: 'user-info', component: () => import('@/views/User/UserInfo.vue') }
      // { path: 'chart', component: () => import('@/views/Chart.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 这里加导航守卫
router.beforeEach((to, from, next) => {
  // to.path 表示即将要访问的路由地址
  // next() 放行：next(false) 不放行，也不跳转 next('/login') 跳转到登录
  if (to.path === '/login' || to.path === '/reg') {
    next() // 如果访问的是登录或注册，放行
  } else {
    // 说明访问的不是登录也不是注册，那就得判断有没有token
    if (store.state.user.token) {
      next()
    } else {
      next('/login ')
    }
  }
})

export default router
